﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.ActionFilter
{
    /*
     * 由于common中不能引用service，Entity搬至各服务中
     使用方式如下
     services.AddMvc(option =>
        {
            option.Filters.Add<CustomActionFilter>();
        });

    实现 WriteLog  
     */
    /// <summary>
    /// action拦截日志记录
    /// </summary>
    public class CustomLogActionFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            string id = context.HttpContext.TraceIdentifier;
            string method = context.HttpContext.Request.Method.ToUpper();
            string url = context.HttpContext.Request.Path.Value;
            string requestData = string.Empty;
            context.HttpContext.Request.EnableBuffering();
            if (context.HttpContext.Request.ContentLength > 0)
            {
                context.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);
                using (StreamReader reader = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8))
                {
                    requestData = reader.ReadToEnd();
                }
            }
            else
            {
                requestData = context.HttpContext.Request.QueryString.Value;
            }
            DateTime startTime = DateTime.Parse(context.HttpContext.Items["StartTime"].ToString());

            TimeSpan timeSpan = DateTime.Now - startTime;

            string str = string.Empty;

            if (context.Result is ObjectResult)
            {
                ObjectResult result = context.Result as ObjectResult;
                str = JsonConvert.SerializeObject(result.Value);
            }
            else if (context.Result is ContentResult)
            {
                ContentResult result = context.Result as ContentResult;
                str = result.Content;
            }
            else if (context.Result is null && context.Exception != null)
            {
                str = context.Exception.Message + "\t" + context.Exception.StackTrace;
            }
            str = str.Replace("\r\n", "").Replace(" ", "");

            WriteLog(id,method,url,requestData, timeSpan.TotalSeconds,str);

        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            context.HttpContext.Items.Add("StartTime", DateTime.Now.ToLongTimeString());
        }
        public void WriteLog(string id, string method, string url, string requestData, double timeConsuming,string responseData) 
        {
            //StringBuilder logstr = new StringBuilder();
            //logstr.AppendLine();
            //logstr.AppendLine("\trequestId：" + id);
            //logstr.AppendLine("\t      Url：" + url);
            //logstr.AppendLine("\t   Method：" + method);
            //logstr.AppendLine("\t     耗时：" + timeSpan.TotalSeconds.ToString() + "秒");
            //logstr.AppendLine("\t     入参：" + requestData);
            //logstr.AppendLine("\t     出参：" + str);
            //Log4NetHelper.Info(logstr.ToString());
        }
    }
}
